package problem.year2021.april;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 给你一个二叉搜索树的根节点 root ，返回 树中任意两不同节点值之间的最小差值。
 * @program: leetcode
 * @author: liangyuan liu
 * @create: 2021-04-13 11:25
 **/
public class April13 {
    public int minDiffInBst(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        transfer(root, list);
        List<Integer> collect = list.stream().sorted().collect(Collectors.toList());
        int min = Integer.MAX_VALUE;
        int len = collect.size();
        for (int i = 1; i < len; i++) {
            min = Math.min(min, collect.get(i) - collect.get(i - 1));
        }
        return min;
    }

    public void transfer(TreeNode treeNode, List<Integer> list) {
        list.add(treeNode.val);
        if (Objects.nonNull(treeNode.left)) {
            transfer(treeNode.left, list);
        }
        if (Objects.nonNull(treeNode.right)) {
            transfer(treeNode.right, list);
        }
    }
}
